package com.fivefu.core.camera.services.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.camera.entity.DbMonitorCamera;
import com.fivefu.core.camera.mapper.DbMonitorCameraMapper;
import com.fivefu.core.camera.services.DbMonitorCameraService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fivefu.core.camera.vo.response.CameraDistributeVo;
import com.fivefu.module.dictionary.entity.DbSysDict;
import com.fivefu.module.dictionary.service.DbSysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 探头表 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-09-19 13:48:32
 */
@Service
public class DbMonitorCameraServiceImpl extends ServiceImpl<DbMonitorCameraMapper, DbMonitorCamera> implements DbMonitorCameraService {

    @Autowired
    private DbSysDictService dbSysDictService;

    /**
     * 通过探头编号查询探头信息
     * @param cameraCode 探头编号
     * @return
     */
    @Override
    public DbMonitorCamera queryMonitorCameraByCode(String cameraCode){
        QueryWrapper<DbMonitorCamera> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("camera_code",cameraCode);
        DbMonitorCamera camera = baseMapper.selectOne(wrapper);
        return camera;
    }

    /**
     * 编辑探头信息
     * @param camera 探头信息
     * @param userid 操作用户编号
     */
    @Override
    public void editMonitorCamera(DbMonitorCamera camera,String userid){
        LocalDateTime time = LocalDateTime.now();
        if (StrUtils.isNotNull(userid)){
            camera.setUpdatedBy(userid);
            camera.setUpdatedTime(time);
        }
        if (camera.getId() != null){
            baseMapper.updateById(camera);
        }else {
            if (StrUtils.isNotNull(userid)){
                camera.setCreatedBy(userid);
                camera.setUpdatedBy(userid);
            }
            camera.setCreatedTime(time);
            camera.setUpdatedTime(time);
            camera.setIsDelete(0);
            baseMapper.insert(camera);
        }
    }

    /**
     * 修改探头在线状态
     * @param id 探头编号
     * @param onlineStatus 在线状态
     */
    @Override
    public void changeCameraOnlineStatus(Long id, String onlineStatus){
        UpdateWrapper<DbMonitorCamera> wrapper = new UpdateWrapper<>();
        wrapper.eq("is_delete", 0);
        wrapper.eq("id", id);
        wrapper.set("online_status", onlineStatus);

        baseMapper.update(null, wrapper);
    }

    /**
     * 查询探头列表
     * @return
     */
    @Override
    public List<DbMonitorCamera> queryMonitorCameraList(){
        QueryWrapper<DbMonitorCamera> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        List<DbMonitorCamera> cameraList = baseMapper.selectList(wrapper);
        return cameraList;
    }

    /**
     * 查询探头部分数据列表
     * @param cameraIDs 探头主键id集合
     * @return
     */
    @Override
    public List<DbMonitorCamera> queryMonitorCameraPartList(List<Long> cameraIDs) {
        QueryWrapper<DbMonitorCamera> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        if (cameraIDs != null && !cameraIDs.isEmpty()){
            wrapper.in("id", cameraIDs);
        }
        wrapper.select("id","camera_code","camera_longitude","camera_latitude","camera_status","camera_name");
        List<DbMonitorCamera> cameraList = baseMapper.selectList(wrapper);
        return cameraList;
    }

    /**
     * 查询探头列表
     * @param cameraName 探头名称(模糊)
     * @param cameraCode 探头编号(模糊)
     * @param cameraType 探头类型
     * @param areaid 所属城区
     * @param streetid 所属街道
     * @param cameraStatus 探头状态
     * @param cameraManufacturer 厂商
     * @param codeList 包含探头编号集合
     * @param excludeCodeList 排除探头编号集合
     * @param page 页码
     * @param limit 数量
     * @return
     */
    @Override
    public Page<DbMonitorCamera> queryCameraList(String cameraName, String cameraCode,String cameraType, String areaid, String streetid,String cameraStatus,String onlineStatus, String cameraManufacturer,
                                                 List<String> codeList, List<String> excludeCodeList, Integer page, Integer limit){
        IPage<DbMonitorCamera> iPage = new Page<>(page, limit);
        Page<DbMonitorCamera> returnPage = baseMapper.queryCameraList(iPage, cameraName, cameraCode,cameraType, areaid, streetid,cameraStatus,onlineStatus, cameraManufacturer, codeList, excludeCodeList);
        return returnPage;
    }


    /**
     *
     * 格式化探头信息
     * @param camera
     */
    @Override
    public Map<String, Object> formatMonitorCamera(DbMonitorCamera camera) {
        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(camera, SerializerFeature.WriteMapNullValue), Map.class);
        if (StrUtils.isNotNull(camera.getCameraType())){
            DbSysDict dict = dbSysDictService.queryDictDetail(null, camera.getCameraType());
            if (dict != null){
                map.put("cameraTypeName",dict.getDictName());
            }
        }
        if (StrUtils.isNotNull(camera.getCameraManufacturer())){
            DbSysDict dict = dbSysDictService.queryDictDetail(null, camera.getCameraManufacturer());
            if (dict != null){
                map.put("cameraManufacturerName",dict.getDictName());
            }
        }
        if (StrUtils.isNotNull(camera.getCameraStatus())) {
            if ("1".equals(camera.getCameraStatus())) {
                map.put("onlineStatusName","在线");
            } else if ("0".equals(camera.getCameraStatus())) {
                map.put("onlineStatusName","离线");
            }
        }
        return map;
    }

    /**
     *
     * 根据探头编号获取监控点位
     *
     */
    @Override
    public List<CameraDistributeVo> queryMonitorPoint(List<Long> cameraIDs) {
        List<CameraDistributeVo> resultList = new ArrayList<>();

        List<DbMonitorCamera> cameras = queryMonitorCameraPartList(cameraIDs);
        if (cameras != null && cameras.size() > 0){
            cameras.forEach(camera -> {
                CameraDistributeVo vo = new CameraDistributeVo();
                vo.setId(camera.getId());
                vo.setCameraCode(camera.getCameraCode());
                vo.setCameraLongitude(camera.getCameraLongitude());
                vo.setCameraLatitude(camera.getCameraLatitude());
                vo.setOnlineStatus(camera.getCameraStatus());
                vo.setCameraName(camera.getCameraName());
                resultList.add(vo);
            });
        }
        return resultList;
    }

    /**
     *
     * 查询监控详情
     * @param cameraId 探头id
     */
    @Override
    public Map<String, Object> queryMonitorPointDetail(Long cameraId) {
        Map<String, Object> detail = new HashMap<>();
        DbMonitorCamera byId = baseMapper.selectById(cameraId);
        if (byId != null){
            detail = formatMonitorCamera(byId);
        }
        return detail;
    }

    /**
     *
     * 通过探头id集合查询其探头编号
     * @param ids
     */
    @Override
    public List<String> queryCameraCodesByIds(List<Long> ids) {
        List<String> list = new ArrayList<>(); // 结果集

        QueryWrapper<DbMonitorCamera> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        if (ids == null || ids.size() <= 0){
            return list;
        }
        wrapper.in("id",ids);

        List<DbMonitorCamera> cameras = list(wrapper);
        //结果转化
        if (cameras != null && cameras.size() > 0){
            for (DbMonitorCamera camera : cameras) {
                if (!list.contains(camera.getCameraCode())){
                    list.add(camera.getCameraCode());
                }
            }
        }
        return list;
    }

    /***
     * 获取探头云图点位分布
     * @param cameraName    探头名称
     * @return
     */
    @Override
    public Map<String,Object> getCameraCloudDistribute(String cameraName) {
        Map<String,Object> resultMap = new HashMap<>();
        List<CameraDistributeVo> resultList = new ArrayList<>();
        int onLineNum = 0;
        int unLineNum = 0;
        resultList =  baseMapper.getCameraCloudDistribute(cameraName);
        if (null != resultList && resultList.size() > 0) {
            for (CameraDistributeVo cameraDistributeVo : resultList) {
                if ("1".equals(cameraDistributeVo.getOnlineStatus())) {
                    onLineNum++;
                } else if ("0".equals(cameraDistributeVo.getOnlineStatus())) {
                    unLineNum++;
                }
            }
        }
        resultMap.put("distribute",resultList);
        resultMap.put("onLineNum",onLineNum);
        resultMap.put("unLineNum",unLineNum);
        return resultMap;
    }
}
